package org.example.xf;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.helper.StringUtil;

/**
 * @Description: TODO
 * @Author wyatt
 * @Data 2024/07/11 19:53
 */
@Slf4j
public class ChatUtil {

    public static final String URL = "https://spark-api-open.xf-yun.com/v1/chat/completions";
    public static final String AUTHORIZATION = "Bearer b78fddd9ac962a77de2207087ba8e250:NDY3MzRiZmIxYzQ3NjNlZjY1ZGE0YjFj";

    private static final String BODY = "{\"model\":\"generalv3.5\",\"messages\":[{\"role\":\"user\",\"content\":\"CONTENTKEY\"}]}";

    public static String chatTranslate(String content){
        if(StringUtil.isBlank(content)){
            return "";
        }
        return retryChat("翻译成中文: ".concat(content));
    }

    public static String chatTranslateSimple(String content){
        if(StringUtil.isBlank(content)){
            return "";
        }
        String res = retryChat("用中文总结下面这段评论（5个字）: ".concat(content));
        return res.substring(0, Math.min(res.length(), 5));
    }

    public static String chatClassify(String content){
        if(StringUtil.isBlank(content)){
            return "";
        }
        String res = retryChat("分析下面这段话，给出4个字分类，只返回4个字: ".concat(content));
        return res.substring(0, Math.min(res.length(), 5));
    }

    public static String chatEvaluate(String content){
        if(StringUtil.isBlank(content)){
            return "";
        }
        String result =  retryChat("分析，返回好评/中评/差评/非评论:  ".concat(content));

        if (result.equals("好评") || result.equals("中评") || result.equals("差评")) {
            return result;
        }

        return "无法评价";
    }

    public static String retryChat(String content){
        int maxRetries = 3; // 设置最大重试次数
        for (int i = 0; i < maxRetries; i++) {
            try {
                // 尝试执行可能会失败的操作
                String result = chat(content);
                if("xf chat error".equals(result)){
                    continue;
                }
                // 如果操作成功，跳出循环
                return result;
            } catch (Exception e) {
                // 如果操作失败，打印错误信息并继续下一次循环尝试
                log.info("操作失败，正在重试...");
            }
        }
        return "xf chat error";
    }

    private static String chat(String content){
        if(StringUtil.isBlank(content)){
            return "";
        }
        long startTime = System.currentTimeMillis();
        try {
           content = content.replaceAll("\"", "").replaceAll("\t", "")
                   .replaceAll("https://", "").replaceAll("http://", "")
                   .replaceAll("Show More", "");
           String bodyNew = BODY.replace("CONTENTKEY", content);
           String result = HttpRequest.post(URL)
                   .body(bodyNew)
                   .header("Content-Type", "application/json")
                   .header("Authorization", AUTHORIZATION)
                   .timeout(10000)
                   .execute().body();

           log.info("chat result : {}", result);
           ChatRep chatRep = JSON.parseObject(result, ChatRep.class );

           long endTime = System.currentTimeMillis();
           long elapsedTime = endTime - startTime;
           String out = chatRep.getChoices().get(0).getMessage().getContent();
           log.info("chat elapsed :{} , in : {}, out : {}", elapsedTime, content, out);
           return out;
       }catch (Exception e) {
           return "xf chat error";
       }
    }

    public static void main(String[] args) {
        System.out.println(chat("翻译成中文： Review my store!!!\thttps://bookalley.in Guys please give your valuable feedback. I am getting traffic but i am not getting any sales."));
    }


}
